package com.example.yls.demoa;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import java.util.ArrayList;

public class StuAdapter extends BaseAdapter {
    private Context context;
    private ArrayList<Student> studentList = new ArrayList<>();
    private IOnDataChangeListener listener;


    public StuAdapter(Context context, ArrayList<Student> studentList, IOnDataChangeListener listener) {
        this.context = context;
        this.studentList = studentList;
        this.listener = listener;
    }

    @Override
    public int getCount() {
        return studentList.size();
    }

    @Override
    public Object getItem(int i) {
        return studentList.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        if (view ==null){
            view = LayoutInflater.from(context).inflate(R.layout.stu_item ,viewGroup,false);

            //组件绑定
            StuViewHolder viewHolder = new StuViewHolder();
            viewHolder.txtNo = view.findViewById(R.id.txt_No);
            viewHolder.txtName = view.findViewById(R.id.txt_Name);
            viewHolder.txtAge = view.findViewById(R.id.txt_Age);
            viewHolder.imgDel = view.findViewById(R.id.img_del);
            //保存viewHolder
            view.setTag(viewHolder);
        }

        //取出当前位置的学生
        final Student student = studentList.get(i);

        //如果view不为空,直接取viewHolder
        StuViewHolder viewHolder = (StuViewHolder) view.getTag();

        //设置数据
        viewHolder.txtNo.setText(student.getStuno());
        viewHolder.txtName.setText(student.getName());
        viewHolder.txtAge.setText(String.valueOf(student.getAge()));

        viewHolder.imgDel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                listener.del(student);
            }
        });

        return view;
    }
}
